package cn.paul.wechatshop.service.impl;

import cn.paul.wechatshop.common.Const;
import cn.paul.wechatshop.common.ServerResponse;
import cn.paul.wechatshop.dao.ProductInfoDao;
import cn.paul.wechatshop.dto.CartDTO;
import cn.paul.wechatshop.entity.ProductInfo;
import cn.paul.wechatshop.exception.WechatshopException;
import cn.paul.wechatshop.service.IProductInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 徐凌峰
 * @date 2017/12/10 0010
 */
@Service
public class ProductInfoServiceImpl implements IProductInfoService {

    @Autowired
    private ProductInfoDao productInfoDao;

    @Override
    public ServerResponse<List<ProductInfo>> findByProductStatus(Integer productStatus) {
        return null;
    }

    @Override
    public ServerResponse<ProductInfo> save(ProductInfo productInfo) {
        return ServerResponse.createBySuccess(productInfoDao.save(productInfo));
    }

    @Override
    public ServerResponse<ProductInfo> findOne(String productId) {
        return ServerResponse.createBySuccess(productInfoDao.findOne(productId));
    }

    @Override
    public ServerResponse<Page<ProductInfo>> findUpAll(Pageable pageable) {
        return ServerResponse.createBySuccess(productInfoDao.findAllByProductStatus(pageable, Const.ProductStatusEnum.ON_SALE.getCode()));
    }

    @Override
    public ServerResponse<Page<ProductInfo>> findAll(Pageable pageable) {
        return ServerResponse.createBySuccess(productInfoDao.findAll(pageable));
    }

    @Override
    public void increaseStock(List<CartDTO> cartDTOList) {
        for (CartDTO cartDTO : cartDTOList) {
            ProductInfo productInfo = productInfoDao.findOne(cartDTO.getProductId());
            if (productInfo == null) {
                throw new WechatshopException(Const.ResultEnum.PRODUCT_NOT_EXITS);
            }
            productInfo.setProductStock(productInfo.getProductStock() + cartDTO.getProductQuantity());
            productInfoDao.save(productInfo);
        }
    }

    @Override
    public void decreaseStock(List<CartDTO> cartDTOList) {
        for (CartDTO cartDTO : cartDTOList) {
            ProductInfo productInfo = productInfoDao.findOne(cartDTO.getProductId());
            if (productInfo == null) {
                throw new WechatshopException(Const.ResultEnum.PRODUCT_NOT_EXITS);
            }
            if (productInfo.getProductStock() < cartDTO.getProductQuantity()) {
                throw new WechatshopException(Const.ResultEnum.PRODUCT_STOCK_NOT_ENOUGH);
            }
            productInfo.setProductStock(productInfo.getProductStock() - cartDTO.getProductQuantity());
            productInfoDao.save(productInfo);
        }

    }
}
